
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sp_util/sp_util.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
import 'package:yp/Xwidgets/button_widget.dart';
import 'package:yp/Xwidgets/cache_image.dart';
import 'package:yp/Xwidgets/line.dart';
import 'package:yp/Xwidgets/pay_bottom_sheet.dart';
import 'package:yp/Xwidgets/shop.dart';
import 'package:yp/config/config.dart';
import 'package:yp/config/rules.dart';
import 'package:yp/config/style.dart';
import 'package:yp/services/api.dart';

import '../../../router.dart';
import 'order_logic.dart';

final List orderStateList = ['待付款', '待发货', '拼团中', '已发货', '待自提', '待评价', '已完成'];

class TuanOrderPage extends StatefulWidget {
  @override
  _OrderPageState createState() => _OrderPageState();
}

class _OrderPageState extends State<TuanOrderPage> with SingleTickerProviderStateMixin {
  TabController _controller;

  var _tabList = [
    Tab(text: '全部'),
    Tab(text: '待付款'),
    Tab(text: '拼团中'),
    Tab(text: '待发货'),
    Tab(text: '待收货'),
  ];

  @override
  void initState() {
    super.initState();

    _controller = TabController(initialIndex: 0, length: _tabList.length, vsync: this);
  }

  @override
  void dispose() async {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final logic = Get.put(OrderLogic());
    final state = Get.find<OrderLogic>().state;

    return Scaffold(
        appBar: AppBar(
          backgroundColor: Config.mainColor,
          brightness: Brightness.light,
          iconTheme: IconThemeData(color: Colors.white),
          title: Text(
            "拼团订单",
            style: TextStyle(color: Colors.white, fontSize: 32.sp),
          ),
          centerTitle: true,
          elevation: 0,
        ),
        body: GetBuilder<OrderLogic>(builder: (logic) {
          return Column(
            children: [
              _tabHeadder(),
              YpLine(
                height: 20,
                thickness: 20,
                color: EsColors.BackGroundSecondary,
              ),
              _orderList(),
            ],
          );
        }));
  }

  /// 获取不同状态下的订单状态数组
  int _getOrderState(int type) {
    switch (type) {
      case 0:
        return 0;
        break;
      case 1:
        return 1;
        break;
      case 2:
        return 2;
        break;
      case 3:
        return 3;
        break;
      case 4:
        return 4;
        break;
      default:
        return 17;
        break;
    }
  }

  ///  tab栏切换的头部
  Widget _tabHeadder() {
    return Container(
      color: EsColors.White,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: ExtendedTabBar(
        tabs: List<Widget>.generate(_controller.length, (int index) => _tabList[index]),
        controller: _controller,
        labelPadding: EdgeInsets.zero,
        labelColor: EsColors.Primary,
        isScrollable: false,
        unselectedLabelColor: EsColors.TitleSecondary,
        indicatorSize: TabBarIndicatorSize.label,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        indicator: const ExtendedUnderlineTabIndicator(
            // size: 30,
            borderSide: BorderSide(color: EsColors.Primary, width: 2)),
      ),
    );
  }

  /// 下边对应的列表
  Widget _orderList() {
    return Expanded(
      child: TabBarView(
          controller: _controller,
          children: List<Widget>.generate(
              _controller.length,
              (int index) => OrderList(
                    orderState: _getOrderState(index),
                    tabIndex: index,
                  )).toList()),
    );
  }
}

class OrderList extends StatefulWidget {
  /// 能够获取的数组  item状态随机
  final int orderState;
  final int tabIndex;

  const OrderList({Key key, this.orderState, this.tabIndex}) : super(key: key);

  @override
  _OrderListState createState() => _OrderListState();
}

class _OrderListState extends State<OrderList> with AutomaticKeepAliveClientMixin {
  List _orderInfoList = [];

  int page = 1;

  RefreshController _refreshController = RefreshController(initialRefresh: true);

  getOrderList() {
    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'user_type': Config.user_type,
      "page_num": page,
      "page_size": 10,
      "customer_order_type": 3,
      "order_status": widget.orderState,
      "channel_num_id": 98
      // 'consumer_name': state.value
    };
    Api.pintuandingdan(params).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          if (event['orders'] != null && event['orders'].length > 0) {
            _orderInfoList.addAll(event['orders']);
            page++;
            _refreshController.refreshCompleted();
            _refreshController.loadComplete();
          } else {
            _refreshController.refreshCompleted();
            _refreshController.loadNoData();
          }
        });
      }
    });
  }

  void _onRefresh() async {
    setState(() {
      _orderInfoList = [];
      page = 1;
    });

    getOrderList();
  }

  void _onLoading() async {
    getOrderList();
  }

  @override
  void initState() {
    super.initState();

    /// Can be set preset time. This case is "00:01.23".
    // _stopWatchTimerDown.setPresetTime(mSec: 1234);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(body: GetBuilder<OrderLogic>(builder: (logic) {
      return SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: ClassicHeader(),
        footer: ClassicFooter(),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.separated(
            itemBuilder: (context, index) {
              return _orderItem(_orderInfoList, index);
            },
            separatorBuilder: (context, index) => YpLine(height: 20, thickness: 20, color: EsColors.BackGroundSecondary),
            itemCount: _orderInfoList.length),
      );
    }));
  }

  /// 订单item
  Widget _orderItem(List info, int index) {
    return GestureDetector(
      onTap: () {
        /// 查看商品详情
        print('跳转订单详情。。。');
        // print(info[index]['tml_num_id']);
        // print(info[index]['order_status']);
        // return;
        Get.toNamed(RouteConfig.orderDetial, arguments: {
          'id': info[index]['tml_num_id'],
          'status:': info[index]['order_status'],
            'info:': info[index],

        });
      },
      child: Container(
        color: EsColors.White,
        padding: const EdgeInsets.only(bottom: 14),
        child: Column(
          children: [
            ShopName(
              info[index]['ec_shop_name'],
              // shopState: info['shopState'],
              orderState: info[index]['order_state_name'],
            ),
            YpLine(),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                Get.toNamed(RouteConfig.orderDetial, arguments: {
                  'id': info[index]['tml_num_id'],
                  'status:': info[index]['order_status'],
                });
                print('查看购买商品');
              },
              child: Container(
                margin: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
                child: Row(
                  children: [
                    Wrap(
                      spacing: 6,
                      children: List.generate(
                      1,
                      (indexs) => CachedImage(
                            width: (MediaQuery.of(context).size.width / 7),
                            height: MediaQuery.of(context).size.width / 7,
                            path: info[index]['image_default_id'],
                            border: Border.all(color: EsColors.BackGroundSecondary, width: 1),
                          )),
                    ),
                      SizedBox(width: 20.w,),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          width: 500.w,
                           height: 50.w,
                          child: Text(info[index]['g_buy_style_name'],maxLines: 1,overflow:TextOverflow.ellipsis ,),
                        ),
                         Container(
                          width: 500.w,
                          child: Text(info[index]['spec_nature_info']==null?'X${info[index]
                                ['qty'].toStringAsFixed(0)}':info[index]
                                ['spec_nature_info']+' X${info[index]
                                ['qty'].toStringAsFixed(0)}',maxLines: 1,overflow:TextOverflow.ellipsis ,),
                        ),
                      ],
                    ),

                    // SizedBox(width: 8),
                    // Text(
                    //   '共1件',
                    //   maxLines: 1,
                    //   overflow: TextOverflow.ellipsis,
                    //   style: TextStyle(color: EsColors.ContentSecondary, fontSize: EsSizes.SM, fontWeight: EsFontWeights.Normal),
                    // )
                  ],
                ),
              ),
            ),
            Row(
              children: [
                SizedBox(width: 12),
                RichText(
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  text: TextSpan(text: '${rules('a1', info[index]) ? '应付' : '实付'}：￥', style: TextStyle(fontSize: EsSizes.XS, color: EsColors.TitleSecondary, fontWeight: EsFontWeights.Normal), children: <TextSpan>[
                    TextSpan(text: rules('a1', info[index]) ? info[index]['trade_price'].toString() : info[index]['trade_price'].toString(), style: TextStyle(fontSize: EsSizes.LG, color: EsColors.TitleSecondary, fontWeight: EsFontWeights.Medium)),
                  ]),
                ),
                Expanded(child: SizedBox()),
                ////按钮
                Padding(
                  padding: const EdgeInsets.only(right: 12),
                  child: _orderProgress(info[index]),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  /// 订单进度 不同状态下的右下角按钮
  Widget _orderProgress(info) {
    return Row(
      children: [
        Visibility(
          visible: rules('a13', info),
          child: Row(children: [
            TimeButton(info, context),
            SizedBox(width: 12.w),
          ]),
        ), //去付款
        // EsOutLineButton(
        //   '订单详情',
        //   normal: true,
        //   onTap: () {
        //     print('订单详情');
        //   },
        // ),
        // SizedBox(width: 12.w),

        Visibility(
          visible: rules('a7', info),
          child: Row(children: [
            EsOutLineButton(
              '拼团详情',
              onTap: () {

                 Get.toNamed(RouteConfig.joinGroup,arguments: {
                   'tml_num_id':info['tml_num_id']
                 });
                print('拼团详情');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        ),

        Visibility(
          visible: rules('a2', info),
          child: Row(children: [
            EsOutLineButton(
              '查看物流',
              normal: true,
              onTap: () {
                Get.toNamed(RouteConfig.logistics, parameters: {'tmlId': info["tml_num_id"], 'transCode': info["ship_tran_no_by_tml_num_ids"]});
                print('查看物流');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        ), //查看物流

        Visibility(
          visible: rules('a3', info),
          child: Row(children: [
            EsOutLineButton(
              '确认收货',
              bgColor: EsColors.Primary,
              textColor: EsColors.White,
              onTap: () {
                print('确认收货');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        ), //确认收货
        Visibility(
          visible: rules('a6', info),
          child: Row(children: [
            RichText(
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              text: TextSpan(text: '自提码：', style: TextStyle(fontSize: EsSizes.XS, color: EsColors.TitleSecondary, fontWeight: EsFontWeights.Normal), children: <TextSpan>[
                TextSpan(text: info['verification_code'].toString(), style: TextStyle(fontSize: EsSizes.LG, color: EsColors.TitleSecondary, fontWeight: EsFontWeights.Medium)),
              ]),
            ),
            SizedBox(width: 12.w),
          ]),
        ), //自提码

        // EsOutLineButton(
        //   '再来一单',
        //   onTap: () {
        //     print('再来一单');
        //   },
        // ),
        // SizedBox(width: 12.w),
        Visibility(
          visible: rules('a5', info) && widget.tabIndex != 5,
          child: Row(children: [
            EsOutLineButton(
              '评价有礼',
              bgColor: EsColors.Primary,
              textColor: EsColors.White,
              onTap: () {
                print('晒单评价');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        ), //评价

        // EsOutLineButton(
        //   '开具发票',
        //   normal: true,
        //   onTap: () {
        //     print('开具发票');
        //   },
        // ),
        // SizedBox(width: 12.w),
      ],
    );
  }

  @override
  void dispose() async {
    super.dispose();
    _refreshController.dispose();

    print('dispose Finish');
  }

  @override
  bool get wantKeepAlive => true;
}

//倒计时按钮
class TimeButton extends StatefulWidget {
  var info;

  TimeButton(this.info, BuildContext context, {Key key}) : super(key: key);

  @override
  _TimeButtonState createState() => _TimeButtonState();
}

class _TimeButtonState extends State<TimeButton> {
  final _isHours = true;

  final StopWatchTimer _stopWatchTimerDown = StopWatchTimer(
    mode: StopWatchMode.countDown,
    presetMillisecond: StopWatchTimer.getMilliSecFromSecond(10),
    // onChange: (value) => print('onChange $value'),
    // onChangeRawSecond: (value) => print('onChangeRawSecond $value'),
    // onChangeRawMinute: (value) => print('onChangeRawMinute $value'),
    onEnded: () {
      print('onEnded');
    },
  );

  @override
  void initState() {
    // Start
    _stopWatchTimerDown.onExecute.add(StopWatchExecute.start);
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() async {
    print('这是销毁');
    super.dispose();
    await _stopWatchTimerDown.dispose(); // Need to call dispose function.
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {},
      child: StreamBuilder<int>(
        stream: _stopWatchTimerDown.rawTime,
        initialData: _stopWatchTimerDown.rawTime.value,
        builder: (context, snap) {
          final value = snap.data;
          // print('value');
          // print(snap);
          final displayTime = StopWatchTimer.getDisplayTime(value, hours: _isHours, milliSecond: false);
          return GestureDetector(
            onTap: () {
              final logic = Get.put(OrderLogic());
              final state = Get.find<OrderLogic>().state;
              logic.state.total['all_payment'] = widget.info['trade_price'];
              print(logic.state.total['all_payment']);
              // return;
              print('card_type:${widget.info['card_type']}');
              print('state.GiftcardList.length:${state.GiftcardList.length}');
              if (state.GiftcardList.length == 0) {
                //直接调起微信支付
                logic.goToMoney(widget.info['tml_num_id']);
              }else{
                  payBottomSheet.showPay(context, logic.state, logic.goToMoney, logic.setGift, tmlnumid: widget.info['tml_num_id']);
              }
              //如果是 0， 需要查询福利卡，减去福利卡金额  （total_amount）- 福利卡金额
              // if (widget.info['card_type'] == 0) {
              //   // 福利卡可多选
              //   // 如果
              //
              // }
            },
            child: Container(
              decoration: BoxDecoration(color: EsColors.Primary, borderRadius: BorderRadius.circular(20.0)),
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              child: Text(
                // '去付款' + displayTime,
                '去付款',
                style: const TextStyle(fontSize: EsSizes.SM, color: EsColors.White, fontWeight: EsFontWeights.Normal),
              ),
            ),
          );
        },
      ),
    );
  }
}
